const network = require('../../utils/network.js')
const loginUtil = require('../../utils/login.js')

Page({

  /**
   * 页面的初始数据
   */
  phoneNum: null,
  code:null,
  checkCode:'',
  data: {
    timer: "获取验证码",
    showPhoneLogin:false,
    showWechatLogin:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.timer = "获取验证码"
  },
  // 发送短信
  sendMsg: function (callback) {
    const params = 'phone=' + this.phoneNum ;
    network.getRequest('mp/simple/client/send', params, (res) => {
      callback();
    })
  },

  getCode: function (e) {
    if (this.phoneNum == '') {
      wx.showToast({
        title: '请输入手机号！',
      })
      return;
    }

    if (this.timer === "获取验证码") {
      this.sendMsg(() => {
        this.timer = 60;
        let t = setInterval(() => {
          this.timer--;
          this.setData({
            timer: "重新获取" + "(" + this.timer + ")"
          })
          if (this.timer === 0) {
            this.timer = "获取验证码";
            this.setData({
              timer: "获取验证码"
            })
            clearInterval(t);
          }

        }, 1000)
      })
    }
  },

// 点击确定
  onGotUserInfo: function (e) {
    var self = this ;
    var checkCode = this.checkCode;
    var phoneNum = this.phoneNum;

    if (phoneNum == null) {
      wx.showToast({
        title: '请输入手机号！',
      })
      return;
    }
    if (checkCode == null) {
      wx.showToast({
        title: '请输入验证码！',
      })
      return;
    }
    wx.login({
      success:function(res){
        self.code = res.code ;
        self.nextTo(e);
      }
    })
  },

  // 验证码登录
  nextTo: function (e) {
    const { encryptedData, iv } = e.detail;
    const params = {
      "userPhone":this.phoneNum,
      "userCode":this.checkCode,
      "code": this.code,
      "encode": {
        "encryptedData": encryptedData,
        "iv": iv
      }
    }
    network.requestLoading('mp/auth/login', params,'登录中',(res)=>{
      setTimeout(()=>{
        wx.showToast({
          title: '登录成功',
        })
      },1000);
      loginUtil.saveLoginInfo(res.data);
      wx.navigateBack({})
    })
  },

  bindPhoneInput: function (e) {
    this.phoneNum = e.detail.value;
  },

  bindCheckCodeInput: function (e) {
    this.checkCode = e.detail.value;
  },

  phoneLoginClick:function(){
    this.setData({
      showPhoneLogin:true
    })
  }
})